<?php

/**
* alltosun.com 商品分类控制器 index.php
* ============================================================================
* 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 吴松键 (wusj@alltosun.com) $
* $Date: 2014-8-8 下午12:36:18 $
* $Id$
*/

class Action
{
    private $per_page = 20;
    /**
     * 显示分类列表
     */
    public function index()
    {
        $res_name      = Request::Get('res_name', 'article');
        $page          = Request::Get('page_no', 1);
        $status        = Request::Get('status', 1);
        $is_advenced   = Request::getParam('is_advenced', 0);
        $search_filter = Request::getParam('search_filter', array());

        // 拼装搜索条件
        $is_empty = 0;
        $filter = array();
        if (isset($search_filter['title']) && $search_filter['title']) {
            $filter['`title` LIKE '] = '%'.$search_filter['title'].'%';
        }
        if (isset($search_filter['start_date']) && $search_filter['start_date']) {
            $filter['`add_time` >'] = $search_filter['start_date'].' 00:00:00';
        }
        if (isset($search_filter['end_date']) && $search_filter['end_date']) {
            $filter['`add_time` <'] = $search_filter['end_date'].' 23:59:59';
        }
        if (isset($search_filter['parent_id']) && $search_filter['parent_id']) {
            $parent_info = _uri('category', $search_filter['parent_id']);
            $parent_filter['`path` LIKE '] = $parent_info['path'].'-'.$parent_info['id'].'%';
            $children_ids = _model('category')->getFields('id', $parent_filter);
            $filter['id'] = $search_filter['parent_id'];
            if ($children_ids) {
                $filter[' OR `id` '] = $children_ids;
            }
        }
        $filter['status'] = $status;
        $filter['res_name'] = $res_name;

        $category_list = array();
        if (!$is_empty) {
            $category_count = _model('category')->getTotal($filter);
            if ($category_count) {
                $pager = new Pager($this->per_page);
                if ($pager->generate($category_count)) {
                    Response::assign('pager', $pager);
                }

                $category_list = _model('category')->getList($filter, " ORDER BY `res_name` DESC,concat(path,'-',id) ASC ".$pager->getLimit($page));
                foreach ($category_list as $key=>$value) {
                    $pathNum = count(explode('-', $value['path']));

                    $prefix = 0;
                    for ($i=0; $i < $pathNum-1; $i++) {
                        $prefix++;
                    }
                    $category_list[$key]['prefix'] = $prefix;
                }
            }
        }

        Response::assign('category_list', $category_list);
        Response::assign('status', $status);
        Response::assign('res_name', $res_name);
        Response::assign('search_filter', $search_filter);
        Response::assign('is_advenced', $is_advenced);

        Response::display('admin/article_category_list.html');
    }

    /**
     * 添加分类
     */
    public function add()
    {
        $res_name = Request::Get('res_name', 'article');

        Response::assign('res_name', $res_name);

        Response::display('admin/article_category_add.html');
    }

    /**
     * 编辑分类
     */
    public function edit()
    {
        $res_name = Request::Get('res_name', 'article');
        $id       = Request::getParam('id', 0);

        $category_info = _uri('category', $id);

        Response::assign('res_name', $res_name);
        Response::assign('category_info', $category_info);
        Response::assign('id', $id);

        Response::display('admin/article_category_add.html');
    }

    /**
     * 保存
     */
    public function save()
    {
        $info = Request::getParam('info', array());
        $id   = Request::getParam('id', 0);

        foreach ($info as $k=>$v) {
            if (!is_numeric($v)) {
                $info[$k] = trim(AnFilter::filter_string($v));
            }
        }

        if (!isset($info['title']) || !$info['title']) {
            return '请填写分类标题';
        }

        if (!isset($info['type']) || !$info['type']) {
            return '请填写分类类型';
        }

        // 查询path
        if ($info['parent_id'] != 0) {
            $parent_info = _uri('category', array('id'=>$info['parent_id']));
            $new_path = $parent_info['path'];
            $info['path'] = $new_path.'-'.$parent_info['id'];
        }else{
            $new_path = '0';
            $info['path'] = 0;
        }

        if ($id) {
            $category_info = _uri('category', $id);
            if (!$category_info) {
                return '该内容不存在';
            }

            if ($info['parent_id'] != $category_info['parent_id']) {
                // 获取所有子分类
                $filter = array(
                        '`path` LIKE ' => $category_info['path'].'-'.$category_info['id'].'%'
                    );

                // 查询分类path
                $old_path_prefix = $category_info['path'].'-'.$category_info['id'];      //原来path前缀
                if ($info['parent_id'] != 0) {
                    $curr_path_prefix  = $parent_info['path'].'-'.$parent_info['id'];    //现在path前缀
                    if ($this->is_contain($curr_path_prefix, $old_path_prefix)) {
                        return '不能移动到自己的子分类中';
                    }
                } else {
                    $curr_path_prefix  = '0';
                }

                // 更新所有子分类的path
                $category_list = _model('category')->getList($filter);
                if ($category_list) {
                    foreach ($category_list as $key=>$value) {
                        $new_path = preg_replace("/^$old_path_prefix/", $curr_path_prefix.'-'.$category_info['id'], $value['path']);
                         _model('category')->update($value['id'], array('path'=>$new_path));
                    }
                }
                $info['path'] = $curr_path_prefix;
            }

            // 更新当前分类信息
            _model('category')->update($id, $info);
        } else {
            _model('category')->create($info);
        }

        Response::redirect(AnUrl('article_category/admin'));
    }

    /**
     * 删除
     * @return array
     */
    public function delete()
    {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k=>$v) {
            if (!$v) {
                continue;
            }

            // 查询是否含有子分类
            $children_info = _uri('category', array('parent_id'=>$v, 'status'=>1));
            if ($children_info) {
                return '请先删除子分类';
            }

            $category_info = _uri('category', $v);
            if (1 == $category_info['status']) {
                _model('category')->update($v, array('status'=>0));
            }
        }

        return 'ok';
    }

    /**
     * 更新状态
     * @return array
     */
    public function change_status()
    {
        $id     = Request::getParam('id', 0);
        $status = Request::getParam('status', 1);
        if (!$id) {
            return '请选择要更改的内容';
        }

        $category_info = _uri('category', $id);
        if ($status == $category_info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        if (1 == $status) {
            _model('category')->update($id, array('status'=>1));
        }

        return 'ok';
    }

    /**
     * ajax分类联动菜单
     */
    public function check_menu()
    {
        $parent_id = Request::getParam('parent_id', 0);
        $res_name = Request::getParam('res_name', '');

        $filter = array(
                'parent_id' => $parent_id,
                'res_name'  => $res_name,
                'status'    => 1
            );

        $category_list = _model('category')->getList($filter, ' ORDER BY `view_order` DESC');
        if (!$category_list) {
            $category_list = array();
        }
        return array('info'=>'ok', 'category_list'=>$category_list);
    }

    /**
     * ajax判断当前分类是否包含子分类
     */
    public function check_end()
    {
        $category_id = Request::getParam('category_id', 0);

        $category_info = _uri('category', array('parent_id'=>$category_id));
        if (!$category_info) {
            return 'ok';
        }
        return 'no_end';
    }

    /**
     * 是否包含字符串
     */
    private function is_contain($curr, $old)
    {
        if (strstr($curr, $old)) {
            $old_arr  = explode('-', $old);
            $curr_arr = explode('-', $curr);
            foreach ($old_arr as $k=>$v) {
                if ($curr_arr[$k] != $v) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}
?>